package com.zx.flow.api.util;

import java.util.Map;
import java.util.Map.Entry;
import org.slf4j.MDC;

/**
 * 直接操作MDC。【与trace无关】
 *
 * @author zhangxue
 */
public class MdcUtil {

    /**
     * 保存信息到上下文
     *
     * @param key
     * @param val
     */
    public static void put(String key, String val) throws IllegalArgumentException {
        if (key == null) {
            throw new IllegalArgumentException("key parameter cannot be null");
        }
        MDC.put(key, val);
    }

    /**
     * 从上下文获取设置的信息
     *
     * @param key
     * @return
     */
    public static String get(String key) throws IllegalArgumentException {
        if (key == null) {
            throw new IllegalArgumentException("key parameter cannot be null");
        }
        return MDC.get(key);
    }

    /**
     * 删除上下文中指定的key的信息
     *
     * @param key
     * @throws IllegalArgumentException
     */
    public static void remove(String key) throws IllegalArgumentException {
        if (key == null) {
            throw new IllegalArgumentException("key parameter cannot be null");
        }
        MDC.remove(key);
    }

    /**
     * 删除所有上下文
     */
    public static void clear() {
        MDC.clear();
    }

    /**
     * 批量保存上下文
     *
     * @param contextMap
     */
    public static void setContextMap(Map<String, String> contextMap) {
        if (contextMap == null) {
            throw new IllegalStateException("contextMap cannot be null");
        }
        for (Entry<String, String> entry : contextMap.entrySet()) {
            MdcUtil.put(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 获得所有上下文
     *
     * @return
     */
    public static Map<String, String> getContextMap() {
        return MDC.getCopyOfContextMap();
    }

}

